package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.etoak.common.constant.CommonConstant;
import com.etoak.common.core.vo.PageVO;
import com.etoak.common.web.context.LoginContext;
import com.etoak.config.OrderQueueConfig;
import com.etoak.dto.OrderDTO;
import com.etoak.entity.Order;
import com.etoak.entity.OrderItem;
import com.etoak.mapper.OrderMapper;
import com.etoak.service.OrderItemService;
import com.etoak.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author et2403
 * @since 2024-08-16
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public void createOrder(OrderDTO orderDTO) {
        //订单编号生成
        String orderNo = IdUtil.getSnowflakeNextIdStr();
        //用户id
        String id = LoginContext.getUserId();
        //创建一个订单并赋予各值
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserId(Integer.parseInt(id));
        order.setOrderState(CommonConstant.ORDER_CREATE_STATE);
        order.setCreateTime(new Date());
        try {
            order.setPrepareTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(orderDTO.getPrepareTime()));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        save(order);

        //保存订单项信息
        List<OrderItem> itemList= orderDTO.getItemList();
        itemList.forEach(orderItem -> orderItem.setOrderNo(orderNo));
        orderItemService.saveBatch(itemList);

        //发送延迟消息
        rabbitTemplate.convertAndSend(OrderQueueConfig.EXCHANGE,OrderQueueConfig.KEY,orderNo,message -> {
            message.getMessageProperties().setDelay(60*10000*5);
            return message;
        });
    }

    @Override
    public PageVO<Order> getList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Order> orderList = baseMapper.getList();

        PageInfo<Order> pageInfo = new PageInfo<>(orderList);
        return new PageVO<>(pageInfo.getPageNum(),pageInfo.getPageSize(),pageInfo.getList(),pageInfo.getTotal());
    }
}
